<template>
    <h1>登录页面</h1>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="username" name="loginname" label="用户名2" placeholder="用户名3"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script>
export default {
    data() {
        return {
            username: "",
            password: ""
        }
    },
    methods: {
        onSubmit(value) {
            console.log("onSubmit", value);
            // {
            //     loginname:"111",
            //     password:"222"
            // }

            this.$http({
                url: "/user/login",
                method: "post",
                data:value
                // data:{
                //     loginname:value.loginname,
                //     password:value.password
                // }
            })
                .then(res => {
                    if(res.data.code==="200"){
                        // 登录成功:
                        // 1、保存用户名                        
                        sessionStorage.setItem("username",value.loginname);
                        sessionStorage.setItem("userid",res.data.data.userid);
                        // 2、保存token
                        sessionStorage.setItem("token",res.data.data.token);
                        // 3、跳转
                        // 3.1）、第一种写法：
                        // const path = this.$route.query.path;
                        // if(path){
                        //     this.$router.push(path);
                        // }else{
                        //     this.$router.push("/");
                        // }
                        // 3.2）、第二种写法：
                        const path = this.$route.query.path || "/";
                        this.$router.push(path);                        
                    }else if(res.data.code==="10010"){
                        Toast('用户名不存在');
                    }else if(res.data.code==="10011"){
                        Toast('密码错误');
                    }
                })
        }
    }
}
</script>

<style>

</style>